﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tunnel.DevicesControls;
using Tunnel.DevicesControls.Lamp;
using Tunnel.Tools.FcmsSupport;

namespace Tunnel
{
    public partial class PlanForm : Form
    {
        public PlanForm()
        {
            InitializeComponent();
        }

        private void PlanForm_Load(object sender, EventArgs e)
        {
            LoadThePlanList();
            lbPlanProgress.Parent = pgPlanRun;
            putLabelPlanInCenter();
            lbPlanProgress.BackColor = System.Drawing.Color.Transparent;
            //LoadThePlanInfoList();
        }
        DataTable dtPlanInfoList;
        DataTable dtPlanList;
        string planListID;
        private Item JX_msg = new Item();
        public void LoadThePlanInfoList()
        {
            string sqlLoadInfoList = "SELECT M_PlanInfo.DeviceID, M_Device.Name, M_PlanInfo.PlanInfo, M_Device.TypeID,M_PlanInfo.PlanPlayList FROM M_PlanInfo LEFT OUTER JOIN M_Device ON M_Device.DeviceID LIKE '%' + M_PlanInfo.DeviceID + '%' WHERE PlanID='" + planListID + "' GROUP BY M_PlanInfo.DeviceID, M_Device.Name, M_Device.TypeID, M_PlanInfo.PlanInfo, M_PlanInfo.Number,M_PlanInfo.PlanPlayList ORDER BY M_PlanInfo.Number";
            SqlDBHelper sdh = new SqlDBHelper();
            dtPlanInfoList = sdh.GetTable(sqlLoadInfoList);

            dataGridView1.Rows.Clear();
            foreach (DataRow dr in dtPlanInfoList.Rows)
            {
                dataGridView1.Rows.Add(1);
                DataGridViewRow lastDr = dataGridView1.Rows[dataGridView1.RowCount - 1];
                lastDr.Cells["设备名称"].Value = dr["Name"].ToString();
                lastDr.Cells["设备状态"].Value = dr["PlanInfo"].ToString();
                lastDr.Cells["设备ID"].Value = dr["DeviceID"].ToString();
                lastDr.Cells["设备类型ID"].Value = dr["TypeID"].ToString();
                lastDr.Cells["播放列表ID"].Value = dr["PlanPlayList"].ToString();
                
            }
        }
        public void LoadThePlanList()
        {
            string sqlLoadPlan = "SELECT M_Plan.* FROM M_Plan";
            SqlDBHelper sdh = new Tunnel.SqlDBHelper();
            dtPlanList = sdh.GetTable(sqlLoadPlan);
            cbPlanList.ValueMember = "PlanID";
            cbPlanList.DisplayMember = "PlanName";
            cbPlanList.DataSource = dtPlanList;
        }

        private void rowInsert_Click(object sender, EventArgs e)
        {
            PlanInfoAdd f = new PlanInfoAdd(this);
            f.StartPosition = FormStartPosition.CenterScreen;
            f.ShowDialog();
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            using (SolidBrush b = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
            {
                e.Graphics.DrawString("第" + (e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture) + "条", new Font("等线", 12, FontStyle.Regular), b, e.RowBounds.Location.X + 17, e.RowBounds.Location.Y + 3);
            }
        }

        private void rowUp_Click(object sender, EventArgs e)
        {
            int rowIndex = dataGridView1.SelectedRows[0].Index;  //得到当前选中行的索引     

            if (rowIndex == 0)
            {
                MessageBox.Show("已经是第一行了!");
                return;
            }

            List<string> list = new List<string>();
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                if (dataGridView1.SelectedRows[0].Cells[i].Value != null)
                {
                    list.Add(dataGridView1.SelectedRows[0].Cells[i].Value.ToString());   //把当前选中行的数据存入list数组中    
                }
                else
                {
                    list.Add("");
                } 
            }
            dataGridView1.Rows[rowIndex].Selected = false;
            for (int j = 0; j < dataGridView1.Columns.Count; j++)
            {
                dataGridView1.Rows[rowIndex].Cells[j].Value = dataGridView1.Rows[rowIndex - 1].Cells[j].Value;
                dataGridView1.Rows[rowIndex - 1].Cells[j].Value = list[j].ToString();
            }
            dataGridView1.Rows[rowIndex - 1].Selected = true;
        }

        private void rowDown_Click(object sender, EventArgs e)
        {
            int rowIndex = dataGridView1.SelectedRows[0].Index;  //得到当前选中行的索引     

            if (rowIndex == dataGridView1.Rows.Count - 1)
            {
                MessageBox.Show("已经是最后一行了!");
                return;
            }

            List<string> list = new List<string>();
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                if (dataGridView1.SelectedRows[0].Cells[i].Value != null)
                {
                    list.Add(dataGridView1.SelectedRows[0].Cells[i].Value.ToString());   //把当前选中行的数据存入list数组中    
                }
                else
                {
                    list.Add("");
                }
            }
            dataGridView1.Rows[rowIndex].Selected = false;
            for (int j = 0; j < dataGridView1.Columns.Count; j++)
            {
                dataGridView1.Rows[rowIndex].Cells[j].Value = dataGridView1.Rows[rowIndex + 1].Cells[j].Value;
                dataGridView1.Rows[rowIndex + 1].Cells[j].Value = list[j].ToString();
            }
            dataGridView1.Rows[rowIndex + 1].Selected = true;
        }

        private void rowDelete_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Remove(dataGridView1.SelectedRows[0]);
        }

        private void cbPlanList_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cbPlanList.SelectedValue != null&&dtPlanList.Rows.Count!=0)
            {
                planListID = cbPlanList.SelectedValue.ToString();
                LoadThePlanInfoList();
                var dr = from s1 in dtPlanList.AsEnumerable()
                         where s1.Field<string>("PlanID") == planListID
                         select s1;
                DataRow s = dr.ToList()[0];
                string _planText = s["PlanText"].ToString();
                planText.Text = _planText;
            }
        }

        private void addPlan_Click(object sender, EventArgs e)
        {
            PlanAdd f = new PlanAdd(this);
            f.StartPosition = FormStartPosition.CenterScreen;
            f.Show();
        }

        private void deletePlan_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确定删除这个预案及其全部内容吗？", "请确认", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                string sqlDeletePlayList = "DELETE FROM M_Plan WHERE PlanID='" + cbPlanList.SelectedValue.ToString() + "'";
                string sqlDeletePlayListInfo = "DELETE FROM M_PlanInfo WHERE PlanID='" + cbPlanList.SelectedValue.ToString() + "'";
                string[] sqlDeleteList = { sqlDeletePlayList, sqlDeletePlayListInfo };
                SqlDBHelper sdh = new SqlDBHelper();
                int count = sdh.ExecteTranCommand(sqlDeleteList);
                if (count != 0)
                {
                    MessageBox.Show("删除成功！");
                }
                LoadThePlanList();

            }
        }

        private void listSave_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("您确定要保存这个预案么？", "预案保存确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.Yes)
            {
                int number = 1;
                List<string> lslist = new List<string>();
                string sqlClear = "delete from M_PlanInfo WHERE PlanID='" + planListID + "'";
                lslist.Add(sqlClear);
                //添加预案内容的SQL语句
                foreach (DataGridViewRow dgvr in dataGridView1.Rows)
                {
                    Global g = new Global();
                    string playlistid;
                    if (dgvr.Cells["播放列表ID"].Value != null)
                    {
                        playlistid = dgvr.Cells["播放列表ID"].Value.ToString();
                    }
                    else
                    {
                        playlistid = "";
                    }
                    string sqlInfoInsert = "INSERT INTO M_PlanInfo(PlanInfoID,PlanID,DeviceID,PlanInfo,PlanPlayList,Number) VALUES ('" + g.CommandID + "','" + planListID + "','" + dgvr.Cells["设备ID"].Value.ToString() + "','" + dgvr.Cells["设备状态"].Value.ToString() + "','" + playlistid + "','" + number + "')";
                    number++;
                    lslist.Add(sqlInfoInsert);
                }
                //修改预案描述的SQL语句
                string sqlUpdatePlanText = "UPDATE M_Plan SET PlanText='" + planText.Text + "' WHERE PlanID='" + planListID + "'";
                lslist.Add(sqlUpdatePlanText);
                //将LIST转化为字符串数组
                string[] sqlListSave = lslist.ToArray();

                SqlDBHelper sdh = new SqlDBHelper();
                int i = sdh.ExecteTranCommand(sqlListSave);
                if (i != 0)
                {
                    MessageBox.Show("已保存该预案，共" + (number - 1).ToString() + "条", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void publishList_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("您确定要运行这个预案么？", "预案运行确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.Yes)
            {
                bwRunPlan.RunWorkerAsync(dataGridView1);
            }
        }

        private void bwRunPlan_DoWork(object sender, DoWorkEventArgs e)
        {
            DataGridView dataGridView1 = e.Argument as DataGridView;
            BackgroundWorker bwRunPlan = sender as BackgroundWorker;
            bwRunPlan.ReportProgress(10, "开始下发指令");
            foreach (DataGridViewRow dgvr in dataGridView1.Rows)
            {
                string deviceName = dgvr.Cells["设备名称"].Value.ToString();
                string deviceStatus = dgvr.Cells["设备状态"].Value.ToString();
                string deviceID = dgvr.Cells["设备ID"].Value.ToString();
                string deviceTypeID = dgvr.Cells["设备类型ID"].Value.ToString();
                string devicePlayListID="";
                if (dgvr.Cells["播放列表ID"].Value != null)
                {
                    devicePlayListID = dgvr.Cells["播放列表ID"].Value.ToString();
                }
                switch (deviceTypeID)
                {
                    case "TS": //交通信号灯段
                        {
                            TS ts = new TS();
                            SqlDBHelper sdh = new SqlDBHelper();
                            string searchParamIDSQL = "select * from R_RunStatus where DeviceID='" + deviceID + "'";
                            DataTable dtParamIDTable = sdh.GetTable(searchParamIDSQL);
                            foreach (DataRow dr in dtParamIDTable.Rows)
                            {

                                switch (dr["ParamStatus"].ToString())
                                {
                                    case "GREEN": ts.GreenID = dr["ParamName"].ToString(); break;
                                    case "RED": ts.RedID = dr["ParamName"].ToString(); break;
                                    case "YELLOW": ts.YellowID = dr["ParamName"].ToString(); break;
                                    case "TURN": ts.TurnID = dr["ParamName"].ToString(); break;
                                }
                            }
                            Global g = new Tunnel.Global();
                            string CommandID = g.CommandID;
                            string redcommand = "INSERT INTO R_Command(CommandID, DeviceID, ParamName, ParamValue, UpdateTime, UpdateBy, Runned) VALUES('" + CommandID + "', '" + deviceID + "', '" + ts.RedID + "', '1', GETDATE(), '" + Global.User + "', 0)";
                            string yellowcommand = "INSERT INTO R_Command(CommandID, DeviceID, ParamName, ParamValue, UpdateTime, UpdateBy, Runned) VALUES('" + CommandID + "', '" + deviceID + "', '" + ts.YellowID + "', '1', GETDATE(), '" + Global.User + "', 0)";
                            string greencommand = "INSERT INTO R_Command(CommandID, DeviceID, ParamName, ParamValue, UpdateTime, UpdateBy, Runned) VALUES('" + CommandID + "', '" + deviceID + "', '" + ts.GreenID + "', '1', GETDATE(), '" + Global.User + "', 0)";
                            switch (deviceStatus)
                            {
                                case "红灯":
                                    {
                                        sdh.ExecuteCommand(redcommand);
                                    }
                                    break;
                                case "黄灯":
                                    {
                                        sdh.ExecuteCommand(yellowcommand);
                                    }
                                    break;
                                case "绿灯":
                                    {
                                        sdh.ExecuteCommand(greencommand);
                                    }
                                    break;
                            }
                        }
                        break;
                    case "FCMS": //情报板段
                        {
                            SqlDBHelper sdh = new SqlDBHelper();
                            Getplaylist getplaylist = new Getplaylist();
                            List<byte> file = new List<byte>();
                            getplaylist.ClearItem();
                            string searchParamIDSQL = "select * from R_FcmsStatus where FCMSID='" + deviceID + "'";
                            DataTable dtParamIDTable = sdh.GetTable(searchParamIDSQL);
                            string selectFcmsParamName = dtParamIDTable.Rows[0]["ParamName"].ToString();
                            string controlSwitch = dtParamIDTable.Rows[0]["ControlSwitch"].ToString();
                            string playlistInfo = "select * from M_PlayListInfo where PlayListID='" + devicePlayListID + "'";
                            DataTable dtPlaylistInfo = sdh.GetTable(playlistInfo);
                            foreach(var item in dtPlaylistInfo.AsEnumerable())
                            {
                                DisplayElement element = new DisplayElement();
                                element.Msg = item["Text"].ToString();
                                element.MsgX = item["TextX"].ToString();
                                element.MsgY = item["TextY"].ToString();
                                element.Delay = (int.Parse(item["StayTime"].ToString()) * 100).ToString();
                                element.FontSize = item["FontSize"].ToString() + item["FontSize"].ToString();
                                element.Colour = item["FontColor"].ToString();

                                getplaylist.AddItem(element);
                            }
                            file = getplaylist.GetPlaylst();
                            using (StreamWriter writer = new StreamWriter(Application.StartupPath + @"\\play.list", false, Encoding.Default))
                            {
                                writer.Write(Encoding.Default.GetString(file.ToArray()));
                                //JX_msg.JX_UploadFile("play.lst", ref file, "");
                                bool successed = JX_msg.JX_UploadFile("play.lst", ref file, deviceID, selectFcmsParamName, controlSwitch);

                            }
                        }
                        break;
                    //照明段
                    case "Light_SunnyS_150W1":
                        {
                            Light_SunnyS1 Lamp = new Light_SunnyS1();
                            SqlDBHelper SDH = new SqlDBHelper();
                            string searchParamIDSQL = "select * from R_RunStatus where DeviceID='Light_SunnyS_150W1'";
                            DataTable dtParamIDTable = SDH.GetTable(searchParamIDSQL);
                            Lamp.ParamID = dtParamIDTable.Rows[0]["ParamName"].ToString();
                            Global g = new Tunnel.Global();
                            string CommandID = g.CommandID;
                            string sqlOn = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','1',GETDATE(),'" + Global.User + "',0)";
                            string sqlOff = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','0',GETDATE(),'" + Global.User + "',0)";
                            switch (deviceStatus)
                            {
                                case "点亮":
                                    {
                                        SDH.ExecuteCommand(sqlOn);
                                    }
                                    break;
                                case "熄灭":
                                    {
                                        SDH.ExecuteCommand(sqlOff);
                                    }
                                    break;
                            }
                        }
                        break;
                    case "Light_CloudS_150W1":
                        {
                            Light_CloudS1 Lamp = new Light_CloudS1();
                            SqlDBHelper SDH = new SqlDBHelper();
                            string searchParamIDSQL = "select * from R_RunStatus where DeviceID='Light_CloudS_150W1'";
                            DataTable dtParamIDTable = SDH.GetTable(searchParamIDSQL);
                            Lamp.ParamID = dtParamIDTable.Rows[0]["ParamName"].ToString();
                            Global g = new Tunnel.Global();
                            string CommandID = g.CommandID;
                            string sqlOn = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','1',GETDATE(),'" + Global.User + "',0)";
                            string sqlOff = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','0',GETDATE(),'" + Global.User + "',0)";
                            switch (deviceStatus)
                            {
                                case "点亮":
                                    {
                                        SDH.ExecuteCommand(sqlOn);
                                    }
                                    break;
                                case "熄灭":
                                    {
                                        SDH.ExecuteCommand(sqlOff);
                                    }
                                    break;
                            }
                        }
                        break;
                    case "Light_SunnyS_150W2":
                        {
                            Light_SunnyS2 Lamp = new Light_SunnyS2();
                            SqlDBHelper SDH = new SqlDBHelper();
                            string searchParamIDSQL = "select * from R_RunStatus where DeviceID='Light_SunnyS_150W2'";
                            DataTable dtParamIDTable = SDH.GetTable(searchParamIDSQL);
                            Lamp.ParamID = dtParamIDTable.Rows[0]["ParamName"].ToString();
                            Global g = new Tunnel.Global();
                            string CommandID = g.CommandID;
                            string sqlOn = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','1',GETDATE(),'" + Global.User + "',0)";
                            string sqlOff = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','0',GETDATE(),'" + Global.User + "',0)";
                            switch (deviceStatus)
                            {
                                case "点亮":
                                    {
                                        SDH.ExecuteCommand(sqlOn);
                                    }
                                    break;
                                case "熄灭":
                                    {
                                        SDH.ExecuteCommand(sqlOff);
                                    }
                                    break;
                            }
                        }
                        break;
                    case "Light_CloudS_150W2":
                        {
                            Light_CloudS2 Lamp = new Light_CloudS2();
                            SqlDBHelper SDH = new SqlDBHelper();
                            string searchParamIDSQL = "select * from R_RunStatus where DeviceID='Light_CloudS_150W2'";
                            DataTable dtParamIDTable = SDH.GetTable(searchParamIDSQL);
                            Lamp.ParamID = dtParamIDTable.Rows[0]["ParamName"].ToString();
                            Global g = new Tunnel.Global();
                            string CommandID = g.CommandID;
                            string sqlOn = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','1',GETDATE(),'" + Global.User + "',0)";
                            string sqlOff = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','0',GETDATE(),'" + Global.User + "',0)";
                            switch (deviceStatus)
                            {
                                case "点亮":
                                    {
                                        SDH.ExecuteCommand(sqlOn);
                                    }
                                    break;
                                case "熄灭":
                                    {
                                        SDH.ExecuteCommand(sqlOff);
                                    }
                                    break;
                            }
                        }
                        break;
                    case "Light_EmergencyLED_50W":
                        {
                            Light_EmergencyLED Lamp = new Light_EmergencyLED();
                            SqlDBHelper SDH = new SqlDBHelper();
                            string searchParamIDSQL = "select * from R_RunStatus where DeviceID='Light_EmergencyLED_50W'";
                            DataTable dtParamIDTable = SDH.GetTable(searchParamIDSQL);
                            Lamp.ParamID = dtParamIDTable.Rows[0]["ParamName"].ToString();
                            Global g = new Tunnel.Global();
                            string CommandID = g.CommandID;
                            string sqlOn = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','1',GETDATE(),'" + Global.User + "',0)";
                            string sqlOff = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','0',GETDATE(),'" + Global.User + "',0)";
                            switch (deviceStatus)
                            {
                                case "点亮":
                                    {
                                        SDH.ExecuteCommand(sqlOn);
                                    }
                                    break;
                                case "熄灭":
                                    {
                                        SDH.ExecuteCommand(sqlOff);
                                    }
                                    break;
                            }
                        }
                        break;
                    case "Light_BasicLED_50W10":
                        {
                            Light_BasicLED10 Lamp = new Light_BasicLED10();
                            SqlDBHelper SDH = new SqlDBHelper();
                            string searchParamIDSQL = "select * from R_RunStatus where DeviceID='Light_BasicLED_50W10'";
                            DataTable dtParamIDTable = SDH.GetTable(searchParamIDSQL);
                            Lamp.ParamID = dtParamIDTable.Rows[0]["ParamName"].ToString();
                            Global g = new Tunnel.Global();
                            string CommandID = g.CommandID;
                            string sqlOn = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','1',GETDATE(),'" + Global.User + "',0)";
                            string sqlOff = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','0',GETDATE(),'" + Global.User + "',0)";
                            switch (deviceStatus)
                            {
                                case "点亮":
                                    {
                                        SDH.ExecuteCommand(sqlOn);
                                    }
                                    break;
                                case "熄灭":
                                    {
                                        SDH.ExecuteCommand(sqlOff);
                                    }
                                    break;
                            }
                        }
                        break;
                    case "Light_BasicLED_50W21":
                        {
                            Light_BasicLED21 Lamp = new Light_BasicLED21();
                            SqlDBHelper SDH = new SqlDBHelper();
                            string searchParamIDSQL = "select * from R_RunStatus where DeviceID='Light_BasicLED_50W21'";
                            DataTable dtParamIDTable = SDH.GetTable(searchParamIDSQL);
                            Lamp.ParamID = dtParamIDTable.Rows[0]["ParamName"].ToString();
                            Global g = new Tunnel.Global();
                            string CommandID = g.CommandID;
                            string sqlOn = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','1',GETDATE(),'" + Global.User + "',0)";
                            string sqlOff = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','0',GETDATE(),'" + Global.User + "',0)";
                            switch (deviceStatus)
                            {
                                case "点亮":
                                    {
                                        SDH.ExecuteCommand(sqlOn);
                                    }
                                    break;
                                case "熄灭":
                                    {
                                        SDH.ExecuteCommand(sqlOff);
                                    }
                                    break;
                            }
                        }
                        break;
                    case "Light_BasicLED_50W22":
                        {
                            Light_BasicLED22 Lamp = new Light_BasicLED22();
                            SqlDBHelper SDH = new SqlDBHelper();
                            string searchParamIDSQL = "select * from R_RunStatus where DeviceID='Light_BasicLED_50W22'";
                            DataTable dtParamIDTable = SDH.GetTable(searchParamIDSQL);
                            Lamp.ParamID = dtParamIDTable.Rows[0]["ParamName"].ToString();
                            Global g = new Tunnel.Global();
                            string CommandID = g.CommandID;
                            string sqlOn = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','1',GETDATE(),'" + Global.User + "',0)";
                            string sqlOff = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','0',GETDATE(),'" + Global.User + "',0)";
                            switch (deviceStatus)
                            {
                                case "点亮":
                                    {
                                        SDH.ExecuteCommand(sqlOn);
                                    }
                                    break;
                                case "熄灭":
                                    {
                                        SDH.ExecuteCommand(sqlOff);
                                    }
                                    break;
                            }
                        }
                        break;
                    case "Light_Out_90W":
                        {
                            Light_Out Lamp = new Light_Out();
                            SqlDBHelper SDH = new SqlDBHelper();
                            string searchParamIDSQL = "select * from R_RunStatus where DeviceID='Light_Out_90W'";
                            DataTable dtParamIDTable = SDH.GetTable(searchParamIDSQL);
                            Lamp.ParamID = dtParamIDTable.Rows[0]["ParamName"].ToString();
                            Global g = new Tunnel.Global();
                            string CommandID = g.CommandID;
                            string sqlOn = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','1',GETDATE(),'" + Global.User + "',0)";
                            string sqlOff = "INSERT INTO R_Command(CommandID,DeviceID,ParamName,ParamValue,UpdateTime,UpdateBy,Runned) VALUES('" + CommandID + "','" + Lamp.DeviceID + "','" + Lamp.ParamID + "','0',GETDATE(),'" + Global.User + "',0)";
                            switch (deviceStatus)
                            {
                                case "点亮":
                                    {
                                        SDH.ExecuteCommand(sqlOn);
                                    }
                                    break;
                                case "熄灭":
                                    {
                                        SDH.ExecuteCommand(sqlOff);
                                    }
                                    break;
                            }
                        }
                        break;
                }
            }
            
            
            bwRunPlan.ReportProgress(30, "风机控制开始");
            int i = 0;  
            foreach (DataGridViewRow dgvr in dataGridView1.Rows)
            {
                string deviceName = dgvr.Cells["设备名称"].Value.ToString();
                string deviceStatus = dgvr.Cells["设备状态"].Value.ToString();
                string deviceID = dgvr.Cells["设备ID"].Value.ToString();
                string deviceTypeID = dgvr.Cells["设备类型ID"].Value.ToString();
                //风机因控制时间问题另行处理
                if (deviceTypeID == "FAN")
                {
                    Fan fan = new Fan();
                    SqlDBHelper SDH = new SqlDBHelper();
                    string sqlSearchParamID = "select * from R_RunStatus where DeviceID='" + deviceID + "'";
                    DataTable dtSearchParam = SDH.GetTable(sqlSearchParamID);
                    foreach (DataRow dr in dtSearchParam.Rows)
                    {
                        switch (dr["ParamStatus"].ToString())
                        {
                            case "ZZ": fan.Zzid = dr["ParamName"].ToString(); break;
                            case "FZ": fan.Fzid = dr["ParamName"].ToString(); break;
                            case "TZ": fan.Tzid = dr["ParamName"].ToString(); break;
                        }
                    }
                    Global g = new Tunnel.Global();
                    string CommandID = g.CommandID;
                    string sqlzz = "INSERT INTO R_Command(CommandID, DeviceID, ParamName, ParamValue, UpdateTime, UpdateBy, Runned) VALUES('" + CommandID + "', '" + deviceID + "', '" + fan.Zzid + "', '1', GETDATE(), '" + Global.User + "', 0)";
                    string sqlfz = "INSERT INTO R_Command(CommandID, DeviceID, ParamName, ParamValue, UpdateTime, UpdateBy, Runned) VALUES('" + CommandID + "', '" + deviceID + "', '" + fan.Fzid + "', '1', GETDATE(), '" + Global.User + "', 0)";
                    string sqltz = "INSERT INTO R_Command(CommandID, DeviceID, ParamName, ParamValue, UpdateTime, UpdateBy, Runned) VALUES('" + CommandID + "', '" + deviceID + "', '" + fan.Tzid + "', '1', GETDATE(), '" + Global.User + "', 0)";

                    int fanSeconds = Tools.FanTimeControl.getSeconds();
                    if (fanSeconds != 0)
                    {
                        System.Threading.Thread.Sleep(fanSeconds * 1000);
                        bwRunPlan.ReportProgress(40 + 10 * i, "正在等待风机控制间隔");
                    }

                    switch (deviceStatus)
                    {
                        case "正转": SDH.ExecuteCommand(sqlzz); break;
                        case "反转": SDH.ExecuteCommand(sqlfz); break;
                        case "停止": SDH.ExecuteCommand(sqltz); break;
                    }
                    Tools.FanTimeControl.LastFanTime = DateTime.Now;
                }
            }
            bwRunPlan.ReportProgress(100, "指令下发完成");
            
        }

        private void bwRunPlan_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int progress = e.ProgressPercentage;
            string progressText = e.UserState as string;
            if(progress>0)
            {
                publishList.Enabled = false;
            }
            pgPlanRun.Value = progress;
            lbPlanProgress.Text = progressText;
            putLabelPlanInCenter();
        }

        private void bwRunPlan_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            publishList.Enabled = true;
            Tools.LogDB.CommandLog("", "", "执行预案[" + cbPlanList.Text + "]");
            MessageBox.Show("预案指令已下发完成");
        }

        private void putLabelPlanInCenter()
        {
            lbPlanProgress.Location = new Point((pgPlanRun.Size.Width - lbPlanProgress.Size.Width) / 2, (pgPlanRun.Size.Height - lbPlanProgress.Size.Height) / 2);
        }
        
    }
}
